package com.cch.platform.web;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.util.Date;

import org.springframework.util.StringUtils;

/**
 * Property editor for Date,<code>java.sql.Timestamp</code>,<br>
 * 字符串格式为毫秒数
 * 
 * @author Barry Chen
 */
public class CustomTimestampEditor extends PropertyEditorSupport {

	private final boolean allowEmpty;

	public CustomTimestampEditor(boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
	}

	public void setAsText(String text) throws IllegalArgumentException {
		if ((this.allowEmpty) && (!(StringUtils.hasText(text)))) {
			setValue(null);
		} else {
			try {
				Long time=Long.parseLong(text);
				setValue(new Timestamp(time));
			} catch (Exception ex) {
				throw new IllegalArgumentException("Could not parse date: "+ ex.getMessage(), ex);
			}
		}
	}

	public String getAsText() {
		String value = ((Timestamp) getValue()).getTime()+"";
		return ((value != null) ? value : "");
	}
}
